import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

const foodsStore = createSlice({
    name: 'foods',
    initialState: {
        // 商品列表
        foodList: [],
        // 菜单激活下标值
        activeIndex: 0,
        // 购物车列表
        cartList: []
    },
    reducers: {
        // 设置商品列表
        setFoodList(state, action) {
            state.foodList = action.payload
        },
        // 更改activeIndex
        changeActiveIndex(state, action) {
            state.activeIndex = action.payload
        },
        // 添加购物车
        addCart(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item) {
                // 该商品已存在，数量加一
                item.count++;
            } else {
                // 该商品不存在，添加到购物车
                action.payload.count = 1
                state.cartList.push(action.payload)
            }
        },
        // 增加购物车数量
        increCount(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            item.count++
        },
        // 减少购物车数量
        decreCount(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            item.count--
            if (item.count === 0) {
                // 数量已经减到0了，把他从购物车中清除掉
                state.cartList = state.cartList.filter(item => item.id !== action.payload.id)
            }
        },
        // 清空购物车
        clearCart(state) {
            state.cartList = []
        }
    }
})

// 解构需要再外部调用的方法
const { setFoodList, changeActiveIndex, addCart, increCount, decreCount, clearCart } = foodsStore.actions

// 异步获取数据
const fetchFoodList = () => {
    // 编写异步函数
    return async (dispatch) => {
        // 同步请求数据
        const res = await axios.get('http://localhost:3004/takeaway')
        // 调用dispatch函数，提交action
        dispatch(setFoodList(res.data))
    }
}

// 将异步获取数据的方法暴露出去
export { fetchFoodList, changeActiveIndex, addCart, increCount, decreCount, clearCart }

// 将状态管理模块暴露出去
const reducer = foodsStore.reducer

export default reducer